<?php

namespace app\stores\controller\miniapp\goods;

use app\BaseController;
use app\beautiful\model\goods\GoodsGroupDetailModel;
use app\beautiful\model\goods\GoodsOtherSkuDetailModel;
use app\beautiful\model\member\MemberModel;
use app\stores\model\goods\GoodsCollectModel;
use app\beautiful\model\logs\GoodsViewsModel;
use app\beautiful\model\mall\GoodsCategoryModel;
use app\beautiful\model\mall\GoodsModel;
use app\beautiful\model\mall\GoodsSkuModel;
use app\common\logic\DataLogic;


class Goods extends BaseController{

    /*获取产品分类*/
    public function getGoodsCategory()

    {
//        $category_id =  $this->request->param('category_id/d',0);

        $return = $this->getCategoryData(0);

        return $this->success($return);

    }

    protected function getCategoryData($pid=0)

    {

        $category= GoodsCategoryModel::where([

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

            ['pid','=',$pid],

            ['type','=',2],

            ['name','<>','套餐']

        ])->order(['sort'=>'desc','add_time'=>'desc'])

            ->field('category_id,name,icon')

            ->select()->toArray();

        if(!empty($category)){

            foreach ($category as $k => $v){

                $category[$k]['children']= $this->getCategoryData($v['category_id']);

            }

        }

        return $category;

    }
    /*获取分类产品*/
    public function getGoodsList()

    {
        $search =  $this->request->param('search');

        $category_id =  $this->request->param('category_id/d',0);

        $where=[

            ['shop_id','=',$this->request->shopId],

            ['status','=',1],

            ['is_delete','=',0],

            ['is_open_yu','=',0],

            ['quota','>',0],

            ['type','=',2]

        ];
        if(!empty($search)) $where[]=['name','like','%'.$search.'%'];

        //查找分类下所有子分类

        $son = GoodsCategoryModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'status'=>1,'pid'=>$category_id])->find();

        if($son){

            $category = GoodsCategoryModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'status'=>1])->select()->toArray();

            $category_ids = $this->get_all_child($category,$category_id);
        }else{
            $category_ids[] =$category_id;
        }

        //获取分类的产品

        $goods_id_arr = [];

        for($i=0;$i<count($category_ids);$i++){

            $goods_ids = GoodsModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'online_sales'=>1])->whereRaw("FIND_IN_SET('{$category_ids[$i]}',category_id)")->column('goods_id');

            $goods_id_arr = array_merge($goods_id_arr,$goods_ids);

        }

        $where[]=['goods_id','IN',$goods_id_arr];

        $order=['sort'=>'desc','fictitious_take_count'=>'desc','vip_price'=>'desc'];

        $goodsModel = GoodsModel::with(['unit','sku'=>function($query){

            $query->with(['unit'=>function($query1){

                $query1->where(['shop_id'=>$this->request->shopId,'is_delete'=>0]);

            }])->where([

                ['shop_id','=',$this->request->shopId],

                ['is_delete','=',0],

                ['quota','>',0],

                ['is_delete','=',0]

            ])->json(['discount_detail'],true);

        }])->json(['discount_detail'],true);

        $field = "is_have_sku,origin_type,type,goods_id,cover_img,name,original_price,crossed_price,vip_price,quota,take_count,fictitious_take_count,category_id,discount_detail,vip_discount_type";

        $append = [];

        $data = DataLogic::getDataList($goodsModel,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        $list = $data['list'];

        $member = $this->request->member;
        if(!$member && $this->request->memberId){
            $member = MemberModel::find($this->request->memberId);
        }
        foreach ($list as $k=>$v){
            $return = getMemberPrice($member,$this->request->shopId,$v,$v['crossed_price'],$v['type']);
            $list[$k]['price'] = $return['price'];
            $list[$k]['discount'] = $return['discount'];
            $list[$k]['unit'] = isset($list[$k]['unit'])?$v['unit']['group_detail_name']:null;
            if($v['is_have_sku']<1){
                $list[$k]['sku'] = [];
            }else{
                if($v['sku']){
                    $sku = skuMemberPrice($v['vip_discount_type'],$v['sku'],$member,$this->request->shopId,$v['type']);
                    $list[$k]['sku'] = $sku;
                }
            }
        }

        $data['list'] = $list;
        return $this->success($data);

    }
    //递归获取所有的子分类的ID
    protected function get_all_child($array,$category_id){
        $arr = array();
        foreach($array as $v){
            if($v['pid'] == $category_id){
                $arr[] = $v['category_id'];
                $arr = array_merge($arr,$this->get_all_child($array,$v['category_id']));
            }
        }
        return $arr;
    }
    /*产品详情*/
    public function getGoodsDetail(){

        $goods_id = $this->request->param('goods_id/d',0);
        //保存用户门店中等级信息
        if($this->request->shopId && $this->request->memberId){
            saveMemberLevel($this->request->shopId,$this->request->memberId);
        }
        if(null === $goods = GoodsModel::with(['unit'])->where(['goods_id'=>$goods_id])->json(['discount_detail','goods_details','products_info'],true)->find()) return $this->error('商品不存在');

        $goods = $goods->toArray();

        if($goods['shop_id'] != $this->request->shopId) return $this->error('商品不存在');

        if($goods['is_delete'] == 1 || $goods['type']!=2) return $this->error('商品不存在');

        if($goods['is_open_yu'] != 0) return $this->error('该商品为预售商品');

        if($goods['status'] != 1) return $this->error('商品已下架');

        $member = $this->request->member;
        if(!$member && $this->request->memberId){
            $member = MemberModel::find($this->request->memberId);
        }
        $return = getMemberPrice($member,$this->request->shopId,$goods,$goods['original_price'],$goods['type']);
        $goods['price'] = $return['price'];
        $goods['discount'] = $return['discount'];

        if($goods['is_have_sku']){
            $sku = GoodsSkuModel::with(['unit'=>function($query){
                    $query->field('other_sku_detail_id,group_detail_name')
                        ->where(['shop_id'=>$this->request->shopId,'is_delete'=>0]);
                }])->where([['goods_id','=',$goods_id],['is_delete','=',0]])
                    ->field('sku_id,unit_id,name,original_price,crossed_price,vip_price,quota,discount_detail,start_sales_num,sku_info,is_by_sales')
                    ->json(['discount_detail'],true)
                    ->select()->toArray() ?? [];

            $sku = skuMemberPrice($goods['vip_discount_type'],$sku,$member,$this->request->shopId,$goods['type']);
        }else{
            $sku = [];
        }

        $detail=[

            'goods_id'=>$goods_id,

            'name'=>$goods['name'],

            'crossed_price'=>$goods['crossed_price'],

            'original_price'=>$goods['original_price'],

            'price'=>$goods['price'],

            'quota'=>$goods['quota'],

            'fictitious_take_count'=>$goods['fictitious_take_count'],

            'vip_price'=>$goods['vip_price'],

            'is_have_sku'=>$goods['is_have_sku'],

            'rotation'=>$goods['rotation'],

            'goods_details'=>$goods['goods_details'],

            'purchase_information' => $goods['purchase_information'],

            'cover_img' => $goods['cover_img'],

            'sku'=>$sku,

            'type'=>$goods['type'],

            'unit'=>isset($goods['unit'])?$goods['unit']['group_detail_name']:null,

            'start_sales_num'=>$goods['start_sales_num'],

            'is_by_sales'=>$goods['is_by_sales'],

            'products_info'=>$goods['products_info'],

            'sku_info'=>$goods['sku_info'],

        ];

        //记录产品的访问记录

        $GoodsViewsModel = new GoodsViewsModel();

        $GoodsViewsModel->save([

            'shop_id'   => $this->request->shopId,

            'goods_id'  => $goods_id

        ]);

        return $this->success(['detail'=>$detail]);



    }




}

